# coding: utf-8
import json
import time
from collections import defaultdict
from s_server.models import *
import requests
from requests.adapters import HTTPAdapter
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


class S_Client(object):
    def __init__(self):
        self.timeout = 20
        self.s = requests.Session()
        self.s.mount("http://", HTTPAdapter(max_retries=5))
        self.s.mount("https://", HTTPAdapter(max_retries=5))
        self.s_day_url = "https://api.biyingapi.com/zs/hfsjy/"
        self.s_list_url = "http://api.biyingapi.com/hslt/list/"
        self.key = "a01016f198e6b5b4"
        self.headers = {
            "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
            "Accept-Encoding": "gzip, deflate",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        }
        self.headers["Content-Type"] = "application/x-www-form-urlencoded"

    def get_s_list_data(self):
        url = self.s_list_url + self.key
        res = self.s.get(
            url,
            headers=self.headers,
            verify=False,
            timeout=self.timeout,
            allow_redirects=False,
        )
        res_json = res.json()
        # print(len(res_json))
        print(res_json)
        data = json.dumps(res_json)
        with open("s_list.json", "w") as f:
            f.write(data)
        return res_json

    def get_single_s_data(self, code):
        # https://api.biyingapi.com/hszbl/fsjy/300750/dq/a01016f198e6b5b4
        s_single_all_url = "https://api.biyingapi.com/zs/hfsjy/{}/dq/{}".format(
            code, self.key
        )
        res = self.s.get(
            s_single_all_url,
            headers=self.headers,
            verify=False,
            timeout=self.timeout,
            allow_redirects=False,
        )
        # print(res.status_code)
        if res.status_code == 500:
            return []

        res_json = res.json()
        return res_json


def get_code_infos():
    client = S_Client()
    gs_list = client.get_s_list_data()
    for i in gs_list:
        # print(i)
        dm = i["dm"]
        mc = i["mc"]
        jys = i["jys"]
        Codes.objects.update_or_create(
            defaults={"mc": mc, "jys": jys},
            dm=dm
        )


from django.db import transaction


def get_stp_infos():
    try:
        print("Start get_stp_infos")
        client = S_Client()
        gs_list = Codes.objects.all()
        gs_code_list = [g.dm for g in gs_list]

        # gs_code_list = ["002251"]
        # print("Start get_stp_infos!!!!!!!!!!!!!!!!!!!!!!!!!!1")
        for dm in gs_code_list:
            time.sleep(0.1)
            print(dm)
            codes_instance = Codes.objects.get(dm=dm)
            s_data = client.get_single_s_data(dm)
            for s in s_data:
                Record.objects.update_or_create(
                    defaults={
                        "o": s["o"],
                        'h': s["h"],
                        'l': s["l"],
                        'c': s["c"],
                        'v': s["v"],
                        'e': s["e"],
                        'zf': s["zf"],
                        'hs': s["hs"],
                        'zd': s["zd"],
                        'zde': s["zde"],
                    },
                    d=s["d"],
                    dm_id=codes_instance
                )


        return True

    except  Exception:
        import traceback
        traceback.print_exc()
    return True
